package com.terry.test2.dp;

import cn.hutool.core.util.ObjectUtil;
import com.terry.test2.old.InsufficientFundsException;
import com.terry.test2.old.InvalidCurrencyException;
import lombok.Data;

import javax.xml.bind.ValidationException;
import java.math.BigDecimal;

/**
 * @author 小八
 * @date 2023年02月01日15:18
 */
@Data
public class Money {
    private BigDecimal amount;
    private Currency currency;

    public Money(BigDecimal amount,Currency currency) throws ValidationException {
        //1.可通过validation  @Empty实现
        if(ObjectUtil.isEmpty(amount)){
            throw new ValidationException("amount不能为空");
        }
        //1.可通过validation  @Empty实现
        if(ObjectUtil.isEmpty(currency)){
            throw new ValidationException("currency不能为空");
        }
        this.currency = currency;
        this.amount = amount;
    }

    public int compareTo(Money money) throws ValidationException {
        //1.可通过validation  @Empty实现
        if(ObjectUtil.isEmpty(money.getCurrency())){
            throw new ValidationException("currency不能为空");
        }
        return amount.compareTo(money.getAmount());
    }


    public void add(Money money){
        //先判断汇率是否一样
        if(!this.getCurrency().equals(money.getCurrency())){
            throw new InvalidCurrencyException();
        }
        this.amount = this.amount.add(money.getAmount());
    }

    public void subtract(Money money) throws ValidationException {
        //先判断汇率是否一样
        if(!this.getCurrency().equals(money.getCurrency())){
            throw new InvalidCurrencyException();
        }
        //判断是否余额够
        if(this.compareTo(money)<0){
            throw new InsufficientFundsException();
        }
        this.amount = this.amount.subtract(money.getAmount());
    }

}
